package com.phantom.reflection;

import java.lang.reflect.Field;

public class ReflectAccessProperty {
    public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("com.phantom.reflection.Student");

        Object o = clazz.newInstance(); // o的运行类型就是student
        System.out.println(o.getClass()); // class com.phantom.reflection.Student

        Field age = clazz.getField("age");
        age.set(o, 18);
        System.out.println(o);
        System.out.println(age.get(o));

        // 通过反射操作name属性
        Field name = clazz.getDeclaredField("name");
        name.setAccessible(true);
        name.set(o, "更木剑八");
        //name.set(null, "更木剑八"); // 因为name是static属性，因此null也可以
        System.out.println(o);


    }
}

class Student {
    public int age;

    private static String name;

    public Student() {
    }

    public Student(int age) {
        this.age = age;
    }


    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name=" + name +
                '}';
    }
}
